<?php
/**
 * Miffos framework
 * ----------------------------------------------
 *
 * Copyright (c) 2008, 2009 Martin Sadový (http://sodae.cz)
 *
 * This source file is subject to the "Miffos license" that is bundled
 * with this package in the file license.txt.
 *
 * @copyright  Copyright (c) 2008, 2009 Martin Sadový
 * @license    license.txt
 * @link       http://miffos.sodae.cz
 * @package    miffos
 * @version    $Id$
 */

abstract class CustomController{

    /**
     * Static instance for Controller
     * @var object
     */
    public static $self;

    /**
     * All loaded model
     * @var object
     */
    public $model;

    /**
     * All loaded control
     * @var object
     */
    public $control;



    public function __construct()
    {
        self::$self              = $this;
        $this->view              = new View($this);
        $this->template          = new Template($this);
        if(method_exists($this,"init"))
            call_user_method("init",$this);
    }



    /**
     * Get Application
     * @return object
     */
    protected function getApplication()
    {
        return Application::get();
    }



    /**
     * Vyhodí instanci pro controller
     * @return object
     */
    public static function get()
    {
        return self::$self;
    }




    /**
     * Rendování controlleru
     */
    public function render()
    {
        $name = Sorter::getAction($this->getApplication()->Router->action,
                                  true,
                                  method_exists($this, Sorter::getAction($this->getApplication()->Router->action, true)
                                  ));
                              
        $this->callMethod($name);

        if(is_null($this->view->service())){
            $this->template->setContent($this->view->render());
            $this->callMethod("beforeRender");
            echo $this->template->render();

        }else{
            echo $this->view->render();
        }
    }




    /**
     * Vyvolá metodu ve zvoleném kontrolleru controlleru ($this||zadanej název)
     * @param string $name
     * @param mixed $controller
     * @param array $arg
     */
    public function callMethod($name,$controller=null,$arg=array())
    {
        if(is_null($controller))
           $controller = $this;

        if(is_string($controller)&&!class_exists($controller,false))
           $this->getApplication()->loadClass("Controller",$controller);

        if(!method_exists($controller,$name))
           throw new ApplicationException("missing-method-".strtolower($name), 2);

        call_user_method_array($name, $controller, $arg);
    }




    /**
     * Načte control
     * @param string $name
     */
    public function loadControl()
    {
        if( !class_exists('Control',false) )
            require_once dirname(__FILE__).'/../Control.php';

        $args = func_get_args();

        if($args[0] == NULL)
            trigger_error('Missing argument 1 for '.__CLASS__.'::loadControl().',E_USER_WARNING);

        $name = $args[0];
        array_shift($args);

        $this->getApplication()->loadClass("Control", $name, 8);

        $nameControlClass = $name."Control";
        $this->control->{$name} = new $nameControlClass($args[0]);
    }



    /**
     * Načte model
     * @param string $name
     */
    public function loadModel($name)
    {
        if( !class_exists('Model',false) ){
            require_once dirname(__FILE__).'/../Model.php';
        }
        $this->getApplication()->loadClass("Model", $name, 4);

        $nameModelClass = $name."Model";
        $this->model->{$name} = new $nameModelClass;
    }



    /**
     * Vytvoří url
     * @param string $url
     * @param array $arg
     * @return string
     */
    public function url($url,$arg=array(),$applink=true)
    {
        if((count($arg) > 0)) $arg = array_merge($this->param(), $arg);
        $url = str_replace("{url}", $this->getApplication()->Http->getRequestUrl(), $url);
        $url = preg_replace('#\<\:(\w+)\>#e', 'isset($arg["\\1"])?$arg["\\1"]:"\\1"', $url);
        return preg_match("/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i", $url)
                ? $url : ($this->getApplication()->Http->getPath(false).$url);
    }




    /**
     * Vypíše parametry z routru
     * @param string $name
     * @return mixed
     */
     public function param($name=null)
     {
        return $this->getApplication()->Router->{$name};
     }



     /**
      * Return data in config 'application'
      * @param string $name
      * @return mixed
      */
     public function getConfig($name = null)
     {
         if(is_null($name)){
             return $this->getApplication()->Config->application;
         }
         return $this->getApplication()->Config->application[$name];
     }



     /**
      * Redirect to url
      * @param string $url
      */
     public function redirect($url,$link=true)
     {
         $this->getApplication()->Http->redirect($link ? $this->url($url) : $url);
     }

     public function beforeRender(){}
}
?>